package api

import (
	"fmt"
	"net"
	"net/http"
	"strings"

	"openzbox.com/frame/echo"
	"openzbox.com/utils"
	//"unsafe"
)

type NetAdapterInfo struct {
	Name       string `json:"name"`
	IP         string `json:"ip"`
	Mac        string `json:"mac"`
	Mask       string `json:"mask"`
	Gateway    string `json:"gateway"`
	NameServer string `json:"nameserver"`
	Flags      string `json:"flags"`
	DHCP       bool   `json:"dhcp"`
}

/*

func getAdapterList() (*syscall.IpAdapterInfo, error) {
	b := make([]byte, 1000)
	l := uint32(len(b))
	a := (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0]))
	err := syscall.GetAdaptersInfo(a, &l)
	if err == syscall.ERROR_BUFFER_OVERFLOW {
		b = make([]byte, l)
		a = (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0]))
		err = syscall.GetAdaptersInfo(a, &l)
	}
	if err != nil {
		return nil, os.NewSyscallError("GetAdaptersInfo", err)
	}
	return a, nil
}
func GetNetInfo(c echo.Context) error {
	var info = make([]NetAdapterInfo, 0)
	fmt.Println("测试基于syscall的getAdapterList()")
	aList, err := getAdapterList()
	if err != nil {
		return err
	}
	for ai := aList; ai != nil; ai = ai.Next {
		fmt.Printf("\nIndex:\t%v\n", ai.Index)
		fmt.Printf("AdapterName:\t%s\n", &ai.AdapterName)
		fmt.Printf("Description:\t%s\n", &ai.Description)
		fmt.Printf("Address:\t%s\n", &ai.Address)
		ipl := &ai.IpAddressList
		gwl := &ai.GatewayList
		dhcpl := &ai.DhcpServer
		for ; ipl != nil; ipl = ipl.Next {
			fmt.Printf("IpAddress:\t%s\n", ipl.IpAddress)
			fmt.Printf("IpMask:\t%s\n", ipl.IpMask)
			fmt.Printf("GatewayIp:\t%s\n", gwl.IpAddress)
			fmt.Printf("DHCPServerIp:\t%s\n", dhcpl.IpAddress)
		}
	}
	return c.JSON(http.StatusOK, info)
}

func GetMACAddress() (string, error) {
	return "", nil
}
*/

func GetNetInfo(c echo.Context) error {
	var info = make([]NetAdapterInfo, 0)
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return c.JSON(http.StatusOK, info)
	}
	//ip route show
	//cat /etc/resolv.conf
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags&net.FlagLoopback) == 0 && strings.Contains(netInterfaces[i].Flags.String(), "broadcast") && !strings.HasPrefix(netInterfaces[i].Name, "dummy") {
			//fmt.Println(netInterfaces[i])
			//fmt.Println(netInterfaces[i].HardwareAddr)
			//fmt.Println(netInterfaces[i].Addrs())
			neti := NetAdapterInfo{}
			neti.Name = netInterfaces[i].Name
			addrs, _ := netInterfaces[i].Addrs()
			if len(addrs) > 0 {
				ip := fmt.Sprintf("%v", addrs[0])
				//	fmt.Println(addrs[0].Network())
				//	fmt.Println(addrs[0].String())
				xip, ipv4Net, err := net.ParseCIDR(ip)
				if err == nil {
					neti.IP = xip.String() //utils.IPv4ToString()
					neti.Mask = utils.IPv4ToString(ipv4Net.Mask)
				}
			}
			neti.Mac = netInterfaces[i].HardwareAddr.String()
			neti.Flags = fmt.Sprintf("%v", netInterfaces[i].Flags)
			info = append(info, neti)
		}
	}
	//fmt.Println(info )
	return c.JSON(http.StatusOK, info)
}
